package org.springblade.modules.ad.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.ldap.support.LdapNameBuilder;

import javax.naming.directory.Attributes;
import javax.naming.ldap.LdapName;
import java.lang.reflect.Field;
import java.util.LinkedList;

public class LdapUtil {

	private static final Logger logger = LoggerFactory.getLogger(LdapUtil.class);

	public static String AD_DN_TYPE_OU = "ou";

	public static String AD_DN_TYPE_CN = "cn";

	/**
	 * 使用LdapName构建器动态构建LdapNameBuilder
	 *
	 * @param pathList ou路径
	 * @param name     添加的域组或用户名称或OU
	 * @param addType  添加的类型是ou还是cn
	 * @return
	 */
	public static LdapName buildDn(LinkedList<String> pathList, String name, String addType) {
		LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance();
		if (CollectionUtil.isNotEmpty(pathList)) {
			for (String str : pathList) {
				ldapNameBuilder.add("ou", str);
			}
		}
		if (!StringUtil.isEmpty(addType)) {
			if (StringUtil.equals(addType, AD_DN_TYPE_CN)) {
				return ldapNameBuilder.add("cn", name).build();
			} else if (StringUtil.equals(addType, AD_DN_TYPE_OU)) {
				return ldapNameBuilder.add("ou", name).build();
			}
		}
		return ldapNameBuilder.build();
	}

	/**
	 * 使用LdapName构建器动态构建LdapNameBuilder
	 *
	 * @param pathList ou路径
	 * @param name     添加的域组或用户名称
	 * @return
	 */
	public static LdapName buildDn(LinkedList<String> pathList, String name) {
		return buildDn(pathList, name, AD_DN_TYPE_CN);
	}


	/**
	 * 对象属性，attributes 映射到对象
	 * @param attributes
	 */
	public static Object objectToContextAttribute(Attributes attributes, Object object) {
		Field[] fields = object.getClass().getDeclaredFields();
		for (int i=0;i<fields.length;i++){
			Field field = fields[i];
			try {
				field.setAccessible(true);
				//logger.info("属性名:" + field.getName() + " 属性值:" + attributes.get(field.getName()));
				if (StringUtil.containsAny("basePath",field.getName())
					|| StringUtil.containsAny("oldBasePath",field.getName())
					|| StringUtil.containsAny("children",field.getName())
					|| (StringUtil.isEmpty(attributes.get(field.getName())))){
					continue;
				}
				field.set(object,attributes.get(field.getName()).get());
			} catch (Exception e) {
				logger.error("对象值转换异常，异常信息" + e.getMessage());
			}
		}
		return object;
	}
}
